package zhihuilan.common.utils;

import com.alibaba.fastjson.JSONObject;
//import com.aliyun.imagesearch20201214.models.*;
import com.aliyun.imageseg20191230.models.SegmentHDCommonImageAdvanceRequest;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeAllTextRequest;
import com.aliyun.ocr_api20210707.models.RecognizeAllTextResponse;
import com.aliyun.searchplat20240529.models.GetTextEmbeddingRequest;
import com.aliyun.searchplat20240529.models.GetTextEmbeddingResponse;
import com.aliyun.searchplat20240529.models.GetTextEmbeddingResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.aliyun.viapi20230117.models.GetAsyncJobResultRequest;
import com.aliyun.viapi20230117.models.GetAsyncJobResultResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;

import com.aliyuncs.alinlp.model.v20200629.GetNerCustomizedChEcomRequest;
import com.aliyuncs.alinlp.model.v20200629.GetNerCustomizedChEcomResponse;
import com.aliyun.imageseg20191230.models.SegmentHDCommonImageResponse;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;


public class AliyunUtils {


    public JSONObject aliNlp(String args, String accessKeyId, String accessKeySecret) throws ClientException {
        DefaultProfile defaultProfile = DefaultProfile.getProfile(
                "cn-hangzhou",
                accessKeyId ,
                accessKeySecret);
        IAcsClient client = new DefaultAcsClient(defaultProfile);
        //构造请求参数，其中GetPosChEcom是算法的actionName, 请查找对应的《API基础信息参考》文档并替换为您需要的算法的ActionName，示例详见下方文档中的：更换API请求
        GetNerCustomizedChEcomRequest request = new GetNerCustomizedChEcomRequest();
        //固定值，无需更改
        request.setSysEndpoint("alinlp.cn-hangzhou.aliyuncs.com");
        //固定值，无需更改
        request.setServiceCode("alinlp");
//        request.setActionName("GetNerCustomizedChEcom");
        //请求参数, 具体请参考《API基础信息文档》进行替换与填写
        request.setText(args);
        request.setLexerId("ECOM");
        long start = System.currentTimeMillis();
        //获取请求结果，注意这里的GetPosChEcom也需要替换
        GetNerCustomizedChEcomResponse response = client.getAcsResponse(request);
        System.out.println(response.hashCode());
        System.out.println(response.getRequestId() + "\n" + response.getData() + "\n" + "cost:" + (System.currentTimeMillis()- start));
        return JSONObject.parseObject(response.getData());
    }

    private Client createClient (String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        config.endpoint="ocr-api.cn-hangzhou.aliyuncs.com";
        return  new Client(config);
    }
    public JSONObject aliCheckBusiness(String url, String accessKeyId, String accessKeySecret) throws Exception {
        Client client = createClient(accessKeyId,accessKeySecret);
        RecognizeAllTextRequest recognizeAllTextRequest = new RecognizeAllTextRequest().setUrl(url).setType("BusinessLicense");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            RecognizeAllTextResponse resp = client.recognizeAllTextWithOptions(recognizeAllTextRequest, runtime);

            System.out.println(com.aliyun.teautil.Common.toJSONString(resp.body.data));
            return JSONObject.parseObject(Common.toJSONString(resp.body.data)) ;
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }


    public JSONObject aliCheckCardId(String url, String accessKeyId, String accessKeySecret) throws Exception {
        Client client = createClient(accessKeyId,accessKeySecret);
        RecognizeAllTextRequest recognizeAllTextRequest = new RecognizeAllTextRequest().setUrl(url).setType("IdCard");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            RecognizeAllTextResponse resp = client.recognizeAllTextWithOptions(recognizeAllTextRequest, runtime);
            return JSONObject.parseObject(Common.toJSONString(resp.body.data)) ;
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }

    public String segmentHDCommonImage (String url, String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "imageseg.cn-shanghai.aliyuncs.com";
        com.aliyun.imageseg20191230.Client client = new com.aliyun.imageseg20191230.Client(config);
        URL urls = new URL(url);
        InputStream inputStream = urls.openConnection().getInputStream();
        SegmentHDCommonImageAdvanceRequest segmentHDCommonImageAdvanceRequest = new SegmentHDCommonImageAdvanceRequest()
                .setImageUrlObject(inputStream);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            SegmentHDCommonImageResponse segmentHDCommonImageAdvanceResponse = client.segmentHDCommonImageAdvance(segmentHDCommonImageAdvanceRequest, runtime);
            String requestId = segmentHDCommonImageAdvanceResponse.getBody().getRequestId();
            return requestId;
            // 获取整体结果。
        } catch (TeaException teaException) {
            // 获取整体报错信息。
            System.out.println(Common.toJSONString(teaException));
            // 获取单个字段。
            System.out.println(teaException.getCode());
        }
        return null;
    }

    public  JSONObject GetAsyncJobResult(String code, String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "viapi.cn-shanghai.aliyuncs.com";
        com.aliyun.viapi20230117.Client client = new com.aliyun.viapi20230117.Client(config);

        GetAsyncJobResultRequest getAsyncJobResultRequest = new GetAsyncJobResultRequest()
                .setJobId(code);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            GetAsyncJobResultResponse getAsyncJobResultResponse = client.getAsyncJobResultWithOptions(getAsyncJobResultRequest, runtime);
            JSONObject imgUrl =JSONObject.parseObject(getAsyncJobResultResponse.getBody().getData().getResult());
            System.out.println(imgUrl);
            return imgUrl;
            // 获取整体结果。
       //     System.out.println(Common.toJSONString(TeaModel.buildMap(segmentHDCommonImageAdvanceResponse)));
        } catch (TeaException teaException) {
            // 获取整体报错信息。
            System.out.println(Common.toJSONString(teaException));
            // 获取单个字段。
            System.out.println(teaException.getCode());
        }
        return null;
    }



    public String stsAliyun( String accessKeyId, String accessKeySecret,String ramRoleArn) {
            String endpoint = "sts.cn-hangzhou.aliyuncs.com";
            String roleArn = ramRoleArn;
            String roleSessionName = "aliyunSts";
            String policy = null;
            Long durationSeconds = 7200L;
            try {
                String regionId = "";
                DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
                IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
                DefaultAcsClient client = new DefaultAcsClient(profile);
                final AssumeRoleRequest request = new AssumeRoleRequest();
                request.setSysMethod(MethodType.POST);
                request.setRoleArn(roleArn);
                request.setRoleSessionName(roleSessionName);
                request.setPolicy(policy);
                request.setDurationSeconds(durationSeconds);
                final AssumeRoleResponse response = client.getAcsResponse(request);
                response.getCredentials().setExpiration((new Date().getTime() / 1000+7000) + "");
                String res =  "{\"Expiration\":" + response.getCredentials().getExpiration()+",\"accessKeyId\":\"" + response.getCredentials().getAccessKeyId()+"\",\"accessKeySecret\":\"" + response.getCredentials().getAccessKeySecret()+"\",\"securityToken\":\"" + response.getCredentials().getSecurityToken()+"\"}";
                return res;
            } catch (ClientException e) {
                System.out.println("Failed：");
                System.out.println("Error code: " + e.getErrCode());
                System.out.println("Error message: " + e.getErrMsg());
                System.out.println("RequestId: " + e.getRequestId());
            }
            return null;
    }

//    public void addImageSearch(MySearch mySearch,String accessKeyId, String accessKeySecret,Integer type) throws Exception {
//        Config authConfig = new Config();
//
//        authConfig.accessKeyId = accessKeyId;
//        authConfig.accessKeySecret = accessKeySecret;
//        authConfig.type = "access_key";
//        authConfig.regionId = "cn-hangzhou"; // 请您更换成您购买实例的区域，例如您购买的实例区域为杭州，则更换为regionId="cn-hangzhou"
//        authConfig.endpoint = "imagesearch.cn-hangzhou.aliyuncs.com"; // 请更换成您购买实例的区域，例如购买的是杭州区域，则endpoint="imagesearch.cn-hangzhou.aliyuncs.com"
//
//       com.aliyun.imagesearch20201214.Client client = new com.aliyun.imagesearch20201214.Client(authConfig);
//        AddImageAdvanceRequest request = new AddImageAdvanceRequest();
//        request.instanceName = "zhlimgsearch001";
//
//        request.productId = mySearch.getPid()+"";
//        request.picName = mySearch.getName();
//        // 选填，图片类目。
//        // 1. 对于商品搜索：若设置类目，则以设置的为准；若不设置类目，将由系统进行类目预测，预测的类目结果可在Response中获取 。
//        // 2. 对于布料、商标、通用搜索：不论是否设置类目，系统会将类目设置为88888888。
//    //    request.categoryId = 3;
//        // 选填，用户自定义的内容，最多支持4096个字符。
//        // 查询时会返回该字段。例如可添加图片的描述等文本。
//        request.customContent = mySearch.getContent();
//        // 选填，整数类型属性，可用于查询时过滤，查询时会返回该字段。
//        // 例如不同的站点的图片/不同用户的图片，可以设置不同的IntAttr，查询时通过过滤来达到隔离的目的
//        request.intAttr = mySearch.getFid();
//        request.intAttr2 = mySearch.getStaffId();
//        request.intAttr3 = type;//0商品  1 附近商店  2 批发商店
//        // 选填，字符串类型属性，最多支持128个字符。可用于查询时过滤，查询时会返回该字段。
//        request.strAttr = mySearch.getLat();
//        request.strAttr2 = mySearch.getLng();
//        request.strAttr3 = mySearch.getDistrictid();
//        request.strAttr4 =  mySearch.getImg().split(",")[0];
//        request.crop = true;
//        // 选填，图片的主体区域，格式为 x1,x2,y1,y2, 其中 x1,y1 是左上角的点，x2，y2是右下角的点。设置的region 区域不要超过图片的边界。
//        // 若用户设置了Region，则不论Crop参数为何值，都将以用户输入Region进行搜索。
//        // 对于布料图片搜索，此参数会被忽略，系统会以整张图进行搜索。
//     //   request.region = "167,467,221,407";
//        RuntimeOptions runtimeOptions = new RuntimeOptions();
//        //String picName = mySearch.getImg().split(",")[0];
//        try {
//            // 图片内容，最多支持 4MB大小图片以及5s的传输等待时间。当前仅支持PNG、JPG、JPEG、BMP、GIF、WEBP、TIFF、PPM格式图片；
//            // 对于商品、商标、通用图片搜索，图片长和宽的像素必须都大于等于100且小于等于4096；
//            // 对于布料搜索，图片长和宽的像素必须都大于等于448且小于等于4096；
//            // 图像中不能带有旋转信息
//
//            // 下方注释代码是URL方式。
//             String url =  mySearch.getImg().split(",")[0];
//             request.picContentObject = new URL(url).openStream();
//
//            //下方为通过图片文件上传。
////            InputStream inputStream = new FileInputStream(picName);
////            request.picContentObject = inputStream;
//            AddImageResponse response = client.addImageAdvance(request,runtimeOptions);
//            System.out.println("success: " + response.getBody().success + ". message: "
//                    + response.getBody().message        + ". categoryId: "
//                    + response.getBody().picInfo.categoryId + ". region:"
//                    + response.getBody().picInfo.region
//                    + ". requestId: " + response.getBody().requestId);
//        } catch (TeaException e) {
//            System.out.println(e.getCode());
//            System.out.println(e.getData());
//            System.out.println(e.getMessage());
//            e.printStackTrace();
//        }
//    }

//    public List<SearchImageByTextResponseBody.SearchImageByTextResponseBodyAuctions> SearchImageByText(MySearchQueryParam queryParam, String accessKeyId, String accessKeySecret) throws Exception{
//            Config authConfig = new Config();
//            authConfig.accessKeyId = accessKeyId;
//            authConfig.accessKeySecret = accessKeySecret;
//            authConfig.type = "access_key";
//            authConfig.regionId = "cn-hangzhou"; // 请您更换成您购买实例的区域，例如您购买的实例区域为杭州，则更换为regionId="cn-hangzhou"
//            authConfig.endpoint = "imagesearch.cn-hangzhou.aliyuncs.com"; // 请更换成您购买实例的区域，例如购买的是杭州区域，则endpoint="imagesearch.cn-hangzhou.aliyuncs.com"
//            com.aliyun.imagesearch20201214.Client client = new com.aliyun.imagesearch20201214.Client(authConfig);
//            SearchImageByTextRequest request = new SearchImageByTextRequest();
//            // 必填，图像搜索实例名称。注意是实例名称不是实例ID。购买后通过 上云层管控台实例信息一栏查看
//            // 注意：本接口仅在服务类型为商品多模态搜索时可以使用。
//            request.instanceName = "zhlimgsearch001";
//            // 选填，返回结果的数目。取值范围：1-100。默认值：10。
//            request.num = Integer.parseInt(queryParam.getPageSize()+"") ;
//            // 选填，返回结果的起始位置。取值范围：0-499。默认值：0。
//            request.start =  Integer.parseInt((queryParam.getPage()-1)*queryParam.getPageSize()+"");
//            // 选填，过滤条件
//            // int_attr支持的操作符有>、>=、<、<=、=，str_attr支持的操作符有=和!=，多个条件之支持AND和OR进行连接。
//            // 示例：
//        System.out.println(queryParam);
//        // 选填，字符串类型属性，最多支持128个字符。可用于查询时过滤，查询时会返回该字段。
//            String filter = "";
//            if(!ObjectUtils.isEmpty(queryParam.getDistrictid())&&queryParam.getDistrictid()>0){
//                filter += "strAttr3 like \""+queryParam.getDistrictid()+"%\" and ";
//            }
//            if(queryParam.getType().equals(1)){
//                filter += "intAttr > 0";
//            }else {
//                filter += "intAttr = 0";
//            }
//        request.filter=filter;
//
//            // 描述文本，支持中英文，最多支持512个字符。
//            request.text = queryParam.getKeyword();
//
//            //选填,若为true则响应数据根据ProductId进行返回。
//            request.distinctProductId=false;
//            try {
//                SearchImageByTextResponse response = client.searchImageByText(request);
//                List<SearchImageByTextResponseBody.SearchImageByTextResponseBodyAuctions> auctions = response.getBody().getAuctions();
//                return auctions;
//            } catch (TeaException e) {
//                System.out.println(e.getCode());
//                System.out.println(e.getData());
//                System.out.println(e.getMessage());
//                e.printStackTrace();
//            }
//        return null;
//    }
//    public List<SearchImageByPicResponseBody.SearchImageByPicResponseBodyAuctions> SearchImageByPic(MySearchQueryParam queryParam, String accessKeyId, String accessKeySecret) throws Exception {
//            Config authConfig = new Config();
//
//            authConfig.accessKeyId = accessKeyId;
//            authConfig.accessKeySecret = accessKeySecret;
//            authConfig.type = "access_key";
//            authConfig.regionId = "cn-hangzhou"; // 请您更换成您购买实例的区域，例如您购买的实例区域为杭州，则更换为regionId="cn-hangzhou"
//            authConfig.endpoint = "imagesearch.cn-hangzhou.aliyuncs.com"; // 请更换成您购买实例的区域，例如购买的是杭州区域，则endpoint="imagesearch.cn-hangzhou.aliyuncs.com"
//
//            //以下为内网（VPC）访问方式
//            // 说明：内网（VPC）访问：仅限同区域ECS或资源的访问，例如您购买的图像搜索实例是华东2（上海），那么您的ECS或资源也必须在华东2（上海）才能通过内网VPC地址访问图搜服务，否则会调用不通，如果遇到调用不通，请先检查您的ECS或资源与图像搜索是否在同一个区域。
//            // authConfig.endpointType = "internal";  // 如果是内网访问图像搜索服务，则endpointType为必填项，值统一为"internal"
//            // authConfig.endpoint = "imagesearch-vpc.cn-shanghai.aliyuncs.com"; // 为内网访问（VPC）地址，请您更换为您购买实例的区域，例如您购买实例的区域为杭州，则endpoint="imagesearch-vpc.cn-hangzhou.aliyuncs.com"
//
//
//            com.aliyun.imagesearch20201214.Client client = new com.aliyun.imagesearch20201214.Client(authConfig);
//            SearchImageByPicAdvanceRequest request = new SearchImageByPicAdvanceRequest();
//            // 必填，图像搜索实例名称。注意是实例名称不是实例ID。购买后通过 上云层管控台实例信息一栏查看
//            request.instanceName = "zhlimgsearch001";
//
//
//            request.crop = true;
//
//            String filter = "";
//            if(!ObjectUtils.isEmpty(queryParam.getDistrictid())&&queryParam.getDistrictid()>0){
//                filter += "strAttr3 like \""+queryParam.getDistrictid()+"%\"";
//            }
//            if(queryParam.getType().equals(1)){
//                filter += "intAttr > 0";
//            }else {
//                filter += "intAttr = 0";
//            }
//            request.filter=filter;
//
//
//            request.num =Integer.parseInt(queryParam.getPageSize()+"") ;
//            request.start = Integer.parseInt(queryParam.getPage()+"") ;
//            //选填,若为true则响应数据根据ProductId进行返回。
//            request.distinctProductId=false;
//            RuntimeOptions runtimeObject =  new RuntimeOptions();
//            try {
//                // 下方注释代码是URL方式。
//                 String url = queryParam.getKeyword();
//                request.picContentObject = new URL(url).openStream();
//
//                //下方为通过图片文件上传。
////                InputStream inputStream = new FileInputStream(picName);
////                request.picContentObject = inputStream;
//                SearchImageByPicResponse response = client.searchImageByPicAdvance(request, runtimeObject);
//                System.out.println(response.getBody().requestId);
//                System.out.println(response.getBody().picInfo.categoryId);
//                System.out.println(response.getBody().picInfo.region);
//                List<SearchImageByPicResponseBody.SearchImageByPicResponseBodyAuctions> auctions = response.getBody().getAuctions();
//                return auctions;
//
//            } catch (TeaException e) {
//                System.out.println(e.getCode());
//                System.out.println(e.getData());
//                System.out.println(e.getMessage());
//                e.printStackTrace();
//            }
//        return null;
//        }

    public List<Float> TextEmbedding(String keyword, String apiKey,String serviceId) throws Exception {

        Config config = new com.aliyun.teaopenapi.models.Config();
        config.setBearerToken(apiKey);
        config.setEndpoint("default-b52w.platform-cn-beijing.opensearch.aliyuncs.com");
        config.setProtocol("http");
        com.aliyun.searchplat20240529.Client client = new com.aliyun.searchplat20240529.Client(config);
        GetTextEmbeddingRequest request = new GetTextEmbeddingRequest()
                .setInput(Arrays.asList(keyword))
                .setInputType("query");
        GetTextEmbeddingResponse response = client.getTextEmbedding("default", serviceId, request);

//        System.out.println(response.getStatusCode());
        List<Float> list = new ArrayList<>();
        for (GetTextEmbeddingResponseBody.GetTextEmbeddingResponseBodyResultEmbeddings embedding : response.getBody().getResult().getEmbeddings()) {
            list =embedding.getEmbedding().stream()
                    .map(Double::floatValue) // 将每个 Double 转为 float（自动装箱为 Float）
                    .collect(Collectors.toList());
//            System.out.println(embedding.getEmbedding());
        }
       return list;
    }
    public List<GetTextEmbeddingResponseBody.GetTextEmbeddingResponseBodyResultEmbeddings> TextSparseEmbedding(String keyword, String apiKey) throws Exception {

        Config config = new com.aliyun.teaopenapi.models.Config();
        config.setBearerToken(apiKey);
        config.setEndpoint("default-b52w.platform-cn-beijing.opensearch.aliyuncs.com");
        config.setProtocol("http");
        com.aliyun.searchplat20240529.Client client = new com.aliyun.searchplat20240529.Client(config);
        GetTextEmbeddingRequest request = new GetTextEmbeddingRequest()
                .setInput(Arrays.asList(keyword))
                .setInputType("document");
        GetTextEmbeddingResponse response = client.getTextEmbedding("default", "ops-text-sparse-embedding-001", request);
        return response.getBody().getResult().getEmbeddings();
//        System.out.println(response.getStatusCode());
//        for (GetTextEmbeddingResponseBody.GetTextEmbeddingResponseBodyResultEmbeddings embedding : response.getBody().getResult().getEmbeddings()) {
//            System.out.println(embedding.getEmbedding());
//        }
    }


}
